﻿///***************************************************************
/// 시  스  템 : Updms.Cfg
/// 단위시스템 : CFG
/// 계      층 : Presentation Layer
/// 프로그램명 : Cfg4010b
/// 파  일  명 : Cfg4010b.aspx.cs
/// 설      명 : 스토어드프로시져
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-10-10 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework;
using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Com.Exe;


namespace Updms.Cfg
{
	public partial class Cfg4010b : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Cfg4010b";
		public static readonly string gs_path_info = "/updms/Cfg/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	//시스템아이디
		protected string kw2 = "";	//SP명
		protected string kw3 = "";	//생성일시작 
		protected string kw4 = "";	//생성일종료
		
		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SelectProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetId();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region SetClientScript

		private void SetClientScript()
		{
			//엔터검색
			txt_search_sp_name.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_create_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_create_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_id.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_id.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_sp_name.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_sp_name.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))
					{
						if (String.IsNullOrEmpty(txt_search_create_dt_from.Text))
						{
							kw3 = "2008-01-01";
							txt_search_create_dt_from.Text = kw3;
						}
						else
						{
							kw3 = txt_search_create_dt_from.Text.Trim();
						}
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_create_dt_from.Text = kw3;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))
					{
						if (String.IsNullOrEmpty(txt_search_create_dt_to.Text))
						{
							kw4 = DateUtil.GetMonthEx(0);	//오늘
							txt_search_create_dt_to.Text = kw4;
						}
						else
						{
							kw4 = txt_search_create_dt_to.Text.Trim();
						}
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						txt_search_create_dt_to.Text = kw4;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_id.SelectedValue;
					kw2 = txt_search_sp_name.Text.Trim();
					kw3 = String.IsNullOrEmpty(txt_search_create_dt_from.Text) ? "2008-01-01" : txt_search_create_dt_from.Text.Trim();
					kw4 = String.IsNullOrEmpty(txt_search_create_dt_to.Text) ? DateUtil.GetMonthEx(0) : txt_search_create_dt_to.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ConversionUtil.CompareReplace(ddl_search_id.SelectedItem.Text, DDL_SELECT, "-");
			lbl_search_keyword.Text = ls_kw1 + " / " + kw2 + " / " + kw3 + " ~ " + kw4;
		}

		#endregion

		#region 마스터 Method (SetId)

		//시스템
		private void SetId()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Com1011m_NT _Com1011m_NT = new Com1011m_NT();

			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			lo_ds.Merge(_Com1011m_NT.GetSystemList(lo_dp));

			// 검색
			ddl_search_id.Items.Clear();
			ddl_search_id.DataSource = lo_ds;
			ddl_search_id.DataMember = "UPDMS_COM_PGM";
			ddl_search_id.DataTextField = "Text";
			ddl_search_id.DataValueField = "Value";
			ddl_search_id.DataBind();
			ddl_search_id.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		#endregion

		#region 디테일 Method (setBatchFileContext, CreateBatchFile)

		//배치파일내용생성
		private string setBatchFileContext()
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("@echo off\r\n");
			sb.Append("REM: Microsoft Visual Database Tools로 만든 명령 파일\r\n");
			sb.Append("REM: 생성 날짜: " + DateUtil.GetNow() + "\r\n");
			sb.Append("REM: 인증 형식: SQL Server\r\n");
			sb.Append("REM: 사용법: CommandFilename [Server] [Database] [Login] [Password]\r\n");

			sb.Append("if '%1' == '' goto usage\r\n");
			sb.Append("if '%2' == '' goto usage\r\n");
			sb.Append("if '%3' == '' goto usage\r\n");

			sb.Append("if '%1' == '/?' goto usage\r\n");
			sb.Append("if '%1' == '-?' goto usage\r\n");
			sb.Append("if '%1' == '?' goto usage\r\n");
			sb.Append("if '%1' == '/help' goto usage\r\n");
			
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_sp_nm = GridView1.Rows[i].Cells[5].Text.ToString();
					sb.Append("osql -S %1 -d %2 -U %3 -P %4 -b -i \"dbo." + ls_sp_nm + ".sql\"\r\n");
					sb.Append("if %ERRORLEVEL% NEQ 0 goto errors\r\n");
				}
			}

			sb.Append("goto finish\r\n");

			sb.Append("REM: 화면 사용법\r\n");
			sb.Append(":usage\r\n");
			sb.Append("echo.\r\n");
			sb.Append("echo 사용법: MyScript Server Database User [Password]\r\n");
			sb.Append("echo Server: 대상 SQL Server 이름\r\n");
			sb.Append("echo Database: 대상 데이터베이스 이름\r\n");
			sb.Append("echo User: 대상 서버에 대한 로그인 이름\r\n");
			sb.Append("echo Password: 대상 서버에 대한 로그인 암호(옵션)\r\n");
			sb.Append("echo.\r\n");
			sb.Append("echo 예: MyScript.cmd MainServer MainDatabase MyName MyPassword\r\n");
			sb.Append("echo.\r\n");
			sb.Append("echo.\r\n");
			sb.Append("goto done\r\n");

			sb.Append("REM: 오류 처리기\r\n");
			sb.Append(":errors\r\n");
			sb.Append("echo.\r\n");
			sb.Append("echo 경고! 오류가 감지되었습니다.\r\n");
			sb.Append("echo --------------------------------\r\n");
			sb.Append("echo 상황을 확인하고 필요하다면\r\n");
			sb.Append("echo 이 명령 파일을 다시 시작하십시오.\r\n");
			sb.Append("echo 이 명령 파일을 실행할 때 명령 매개 변수를\r\n");
			sb.Append("echo 입력해야 합니다.\r\n");
			sb.Append("echo.\r\n");
			sb.Append("pause\r\n");
			sb.Append("goto done\r\n");

			sb.Append("REM: 실행 완료\r\n");
			sb.Append(":finish\r\n");
			sb.Append("echo.\r\n");
			sb.Append("echo 스크립트를 실행했습니다.\r\n");
			sb.Append(":done\r\n");
			sb.Append("@echo on\r\n");			
			
			return sb.ToString();
		}

		//실제배치파일생성
		private void CreateBatchFile()
		{
			try
			{
				string ls_stream = FILE_PATH_TEMP + "UPDMS_DB_OBJECT_LIST.bat";
				FileInfo file = new FileInfo(ls_stream);

				StreamWriter sw = file.CreateText();
				sw.WriteLine(setBatchFileContext());
				sw.Close();

				if (FileUtil.IsFileExist(ls_stream))
				{
					CallMsgBoxInAjax("MSG_INF_011");	//파일이 생성되었습니다
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_122");	//파일을 생성하지 못했습니다
				}
			}
			catch (Exception e)
			{
				SMEventLog.WriteExceptionLog(e);
				CallMsgBoxInAjax("MSG_ERR_122");	//파일을 생성하지 못했습니다
			}
		}

		#endregion

		#region CRUDS (SelectProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_sp_name", typeof(string), kw2);
			lo_dp.AddProperty("ls_create_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_create_dt_to", typeof(string), kw4);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Com1011m_NT _Com1011m_NT = new Com1011m_NT())
			{
				lo_ds.Merge(_Com1011m_NT.GetUpdmsStoredprocedureList(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = DataSetUtil.GetRowCount(lo_ds, "UPDMS_COM_PGM").ToString();
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();

			SelectProcess();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();	//번호
				e.Row.Cells[7].Attributes.Add("class", (e.Row.Cells[7].Text == "Y") ? "color_darkred" : "color_gray"); //사용여부
				e.Row.Cells[8].Text = "<div class=\"sbtn sbtn_new_window\" onclick=\"javascript:showStoredProcedure('" + e.Row.Cells[5].Text + "');\" />";
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 2);
			sGv.RowSpanGridView(GridView1, 3);
			sGv.RowSpanGridView(GridView1, 4);
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_sp_name", typeof(string), kw2);
			lo_dp.AddProperty("ls_create_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_create_dt_to", typeof(string), kw4);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Com1011m_NT _Com1011m_NT = new Com1011m_NT())
			{
				lo_ds.Merge(_Com1011m_NT.GetUpdmsStoredprocedureList(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//생성
		protected void ibtn_create_Click(object sender, EventArgs e)
		{
			CreateBatchFile();
		}

		#endregion

	}
}
